var createToolsBar = (type, array) => {
    // 生成工具条
    // 添加常用功能 按钮
    let tools = document.createElement('div');
    tools.className = "drag-tools-bar";

    tools.setAttribute("data-type", type);
    
    var created = function(txt, type){
        let btn = document.createElement('div');
        let btnIcon = document.createElement('i');
        btnIcon.className = "el-icon-"+type;
        btnIcon.innerHTML = txt;
        btn.className = "layout-box-btn-"+type;
        btn.appendChild(btnIcon);
        return btn;
    }

    array.forEach(element => {
        if(element == 'delete'){
            tools.appendChild(created('删除', 'delete'));
        }else if(element == 'edit'){
            tools.appendChild(created('编辑', 'edit'));
        }else if(element == 'document-add'){
            tools.appendChild(created('添加', 'document-add'));
        }else if(element == 'thumb'){
            tools.appendChild(created('拖动', 'thumb'));
        }
    });
    
    return tools;
}
var getBoolean = (string) => {
    if(string == 'true'){
        return true;
    }else{
        return false;
    }
}
export default {
    /**
     * 解析properties文件
    */
    parseFileProperties: (value) => {
        let array = value.split(/[\s\n]/);
        let json = {};
        array.forEach(element => {
            if(element.length > 0){
                json[element.split("=")[0]] = unescape(element.split("=")[1] ? element.split("=")[1].replace(/\\u/g, '%u') : '');
            }
        });
        return json;
    },
    /**
     * 解析xml文件
    */
    parseFileXml: (options) =>{
        // console.log(options);
        let pages = options.xmlJson.pages || {};
        let res = {};
        let time = +new Date();
        var inputAdd = (array, value, type) => {
            // 添加form表单
            array.push({
                value: '',
                label: value._title,
                field: value._title,
                row: parseInt(value._row),
                col: parseInt(value._col),
                span: parseInt(value._span) ? parseInt(value._span) : 1,
                type: type, // 标签类型
                readOnly: getBoolean(value._readOnly),//只读
                required: getBoolean(value._required),//必填
                reserve: getBoolean(value._reserve),//是否重置控件
                forceOverride: getBoolean(value._forceOverride),//强制更新
                focusUI: getBoolean(value._focusUI),//聚焦
                inVisible: getBoolean(value._inVisible),//是否隐藏
                validator: value._validator,//数据校验
                // 远程查找框属性             
                multiple: getBoolean(value._multiple),//多选
                manualEditable: getBoolean(value._manualEditable),//可编辑
                defaultCurrentDate: getBoolean(value._defaultCurrentDate), // 默认当前日期
                displayColumn: value._displayColumn, //显示列数
                percentSignPosition: value._percentSignPosition,  //模糊查询
                displayedTableHead: value._displayedTableHead, // 查找框标题,
                hsql: value.dataValue || value.hql,
                visibleExpression: "",
                eventListeners: ""
            })
        }
        for(let key in pages){
            options.global.pageType = key; // 页面类型
            options.global.page = pages[key]._id || "";
            options.global.onClose = pages[key]._onClose || "";
            options.global.entityClass = pages[key]._entityClass || "";
            options.global.autoQuery = pages[key]._autoQuery || "";
            options.global.width = pages[key]._width || "";
            options.global.height = pages[key]._height || "";
            options.global.datasource = pages[key].datasource || "";
            options.global.initListeners = pages[key].initListeners || "";
            options.global.workflow = pages[key].workflow || "";

            // 如果存在inputUIs
            let inputUIs = pages[key].inputUIs ? pages[key].inputUIs : pages[key].modify ? pages[key].modify.inputUIs : null;
            if(inputUIs){
                let inputsArray = {
                    id: 'form' + time,
                    keywordsTextareaHsql: "",
                    row: 4,
                    inputComWidth: 200,
                    forms: [],
                    hidden: null
                };
                let maxRow = 0;
                for(let ik in inputUIs){
                    if(ik == 'hidden'){
                        inputsArray.hidden = {
                            id: inputUIs[ik]._id,
                            reserve: inputUIs[ik]._reserve,
                            title: inputUIs[ik]._title
                        }
                    }else{
                        let type = Object.prototype.toString.call(inputUIs[ik]).indexOf('Array') >= 0;
                        if(type){
                            // 如果是数组。
                            for(let i in inputUIs[ik]){
                                parseInt(inputUIs[ik][i]._col) >= maxRow ? maxRow = parseInt(inputUIs[ik][i]._col) : null;
                                inputAdd(inputsArray.forms, inputUIs[ik][i], ik);
                            }
                        }else{
                            // 如果是单个的。
                            parseInt(inputUIs[ik]._col) >= maxRow ? maxRow = parseInt(inputUIs[ik]._col) : null;
                            inputAdd(inputsArray.forms, inputUIs[ik], ik);
                        }
                    }
                }
                inputsArray.row = maxRow;
                res['inputsArray'] = inputsArray;
            }
            if(key == "maintainPage" || key == "modifyDetailPage"){
                let columns = pages[key].columns ? pages[key].columns : pages[key].detail.columns;
                console.log("pages[key]",pages[key])
                let tableArray = {
                    id: 'table' + time,
                    keywordsTextareaHsql: pages[key].datasource ? pages[key].datasource : pages[key].detail.datasource,
                    entityClass: pages[key]._entityClass ? pages[key]._entityClass : pages[key].detail._entityClass,
                    autoQuery: pages[key]._autoQuery ? pages[key]._autoQuery : pages[key].detail._autoQuery,
                    columns: []
                }
                columns.column.forEach(element => {
                    tableArray.columns.push({
                        prop: element._id, 
                        label: element._title,
                        width: element._width,
                        visible: getBoolean(element._visible),
                        sortable: getBoolean(element._sortable),
                        horizonAlign: element._horizonAlign,
                        verticalAlign: element._verticalAlign,
                        dataType: element._dataType,
                        format: element._format, 
                        formatParam: element._formatParam, 
                        language: getBoolean(element._language)
                    });
                });
                res['tableArray'] = tableArray;
            }
            if(key == "modifyMultiDetailPage"){
                // let detail = page.getElementsByTagName("detail");
                let details = pages[key].details.detail;
                let tabsArray = {
                    id: 'tabs' + time,
                    tabs: []
                };
                details.forEach((element, index) => {
                    let columns = element.columns.column;
                    // hsql语句在这儿
                    tabsArray.tabs.push({
                        id: element._tabId,
                        keywordsTextareaHsql: element.datasource,
                        tabsLabel: element._tabId,
                        tabsPorp: element._tabId,
                        autoQuery: element._autoQuery,
                        entityClass: element._entityClass,
                        columns: []
                    });
                    columns.forEach(ele => {
                        tabsArray.tabs[index].columns.push({
                            prop: ele._id, 
                            label: ele._title,
                            width: ele._width,
                            visible: getBoolean(ele._visible),
                            sortable: getBoolean(ele._sortable),
                            horizonAlign: ele._horizonAlign,
                            verticalAlign: ele._verticalAlign,
                            dataType: ele._dataType,
                            format: ele._format, 
                            formatParam: ele._formatParam, 
                            language: getBoolean(ele._language)
                        });
                    });
                });
                res["tabsArray"] = tabsArray;
            }
        }

        return res;
        // let div = document.createElement('div');
        // div.innerHTML = options.xml;
        // let page = div.children && div.children[0];
        // if(page){
        //     let pageChild = page.children[0];
        //     let localName = pageChild.localName;
        //     console.log(localName)
        //     // 全局变量设置
        //     if(pageChild){
        //         options.global.page = pageChild.id;
        //         options.global.onClose = pageChild.getAttribute("onClose");
        //         options.global.entityClass = pageChild.getAttribute("entityClass");
        //         options.global.autoQuery = pageChild.getAttribute("autoQuery");
        //         options.global.width = pageChild.getAttribute("width");
        //         options.global.height = pageChild.getAttribute("height");
        //         if(localName == 'maintainpage'){
        //             options.global.pageType = "maintainPage";
        //         }else if(localName == 'editpage'){
        //             options.global.pageType = "editPage";
        //         }else if(localName == 'modifydetailpage'){
        //             options.global.pageType = "modifyDetailPage";
        //         }else if(localName == 'modifymultidetailpage'){
        //             options.global.pageType = "modifyMultiDetailPage";
        //         }
        //     }
        //     // inputuis
        //     let inputuis = page.getElementsByTagName("inputuis")[0];
        //     if(inputuis){
        //         let inputs = inputuis.children[0].children;
        //         let inputsArray = {
        //             id: 'form' + time,
        //             keywordsTextareaHsql: "",
        //             row: 4,
        //             inputComWidth: 200,
        //             forms: []
        //         };
        //         let maxRow = 0;
        //         inputs.forEach(element => {
        //             let localName = element.localName;
        //             if(localName == 'numbertext'){
        //                 localName = 'numberText';
        //             }
        //             if(parseInt(element.getAttribute("col")) >= maxRow){
        //                 maxRow = parseInt(element.getAttribute("col"));
        //             }
        //             inputsArray.forms.push({
        //                 label: element.title,
        //                 value: '',
        //                 field: element.id,
        //                 row: parseInt(element.getAttribute("row")),
        //                 col: parseInt(element.getAttribute("col")),
        //                 span: element.getAttribute("span") ? parseInt(element.getAttribute("span")) : 1,
        //                 type: localName,
        //                 readOnly: getBoolean(element.getAttribute("readOnly")),//只读
        //                 required: getBoolean(element.getAttribute("required")),//必填
        //                 reserve: getBoolean(element.getAttribute("reserve")),//是否重置控件
        //                 forceOverride: getBoolean(element.getAttribute("forceOverride")),//强制更新
        //                 focusUI: getBoolean(element.getAttribute("focusUI")),//聚焦
        //                 inVisible: getBoolean(element.getAttribute("inVisible")),//是否隐藏
        //                 validator: element.getAttribute("validator"),//数据校验
        //                 // 远程查找框属性             
        //                 multiple: getBoolean(element.getAttribute("multiple")),//多选
        //                 manualEditable: getBoolean(element.getAttribute("manualEditable")),//可编辑
        //                 defaultCurrentDate: getBoolean(element.getAttribute("defaultCurrentDate")), // 默认当前日期
        //                 displayColumn: element.getAttribute("displayColumn"), //显示列数
        //                 percentSignPosition: element.getAttribute("percentSignPosition"),  //模糊查询
        //                 displayedTableHead: element.getAttribute("displayedTableHead"), // 查找框标题,
        //                 hsql: ""
        //             });
        //         });
        //         inputsArray.row = maxRow;
        //         res['inputsArray'] = inputsArray;
        //     }
        //     // maintainpage
        //     if(localName == "maintainpage"){
        //         let tableArray = {
        //             id: 'table'+time,
        //             keywordsTextareaHsql: "",
        //             columns: []
        //         }
        //         let columns = page.getElementsByTagName("columns")[0].getElementsByTagName("column");
        //         columns.forEach(element => {
        //             tableArray.columns.push({
        //                 prop: element.id, 
        //                 label: element.title,
        //                 width: element.getAttribute("width"),
        //                 visible: getBoolean(element.getAttribute("visible")),
        //                 sortable: getBoolean(element.getAttribute("sortable")),
        //                 horizonAlign: element.getAttribute("horizonAlign"),
        //                 verticalAlign: element.getAttribute("verticalAlign"),
        //                 dataType: element.getAttribute("dataType"),
        //                 format: element.getAttribute("format"), 
        //                 formatParam: element.getAttribute("formatParam"), 
        //                 language: getBoolean(element.getAttribute("language"))
        //             });
        //         });
        //         res['tableArray'] = tableArray;
        //     }
        //     if(localName == "modifydetailpage"){
        //         let datasource = page.getElementsByTagName("datasource")[0];
        //         let detail = page.getElementsByTagName("detail")[0].getElementsByTagName("column");
        //         let tableArray = {
        //             id: 'table' + time,
        //             keywordsTextareaHsql: "",
        //             columns: []
        //         }
        //         detail.forEach(element => {
        //             tableArray.columns.push({
        //                 prop: element.id, 
        //                 label: element.title,
        //                 width: element.getAttribute("width"),
        //                 visible: getBoolean(element.getAttribute("visible")),
        //                 sortable: getBoolean(element.getAttribute("sortable")),
        //                 horizonAlign: element.getAttribute("horizonAlign"),
        //                 verticalAlign: element.getAttribute("verticalAlign"),
        //                 dataType: element.getAttribute("dataType"),
        //                 format: element.getAttribute("format"), 
        //                 formatParam: element.getAttribute("formatParam"), 
        //                 language: getBoolean(element.getAttribute("language"))
        //             });
        //         });
        //         res['tableArray'] = tableArray;
        //     }
        //     if(localName == "modifymultidetailpage"){
                
        //     }
        // }
        // console.log(res)
        // return res;
    },
    /**
     * 拖动布局框成dom
    */
	menuLayout: (array) => {
        let div = document.createElement('div');
		div.className = "layout-box components-box";//设置div的属性，如：class，title，id 等等
        
        div.appendChild(createToolsBar('builderBox', ['delete', 'thumb']));
        
        // 根据分隔数量添加子元素
        for(let i in array){
            let kids = document.createElement('div');
            kids.className = "layout-box-kids layout-box-kids-" + array[i];//设置div的属性，如：class，title，id 等等
            kids.setAttribute("data-type", "LayoutBox");
            kids.setAttribute("data-components", "ComponentsBox");
            div.appendChild(kids);
        }
        
        return div;
    },
    /**
     * 拖动组件成dom
    */
    componentsDom: (options)=>{
        let div = document.createElement('div');
        div.classList = 'layout-components-box';
        
        if(options.type == 'table'){
            div.setAttribute('data-componentstype', 'table');
            div.setAttribute('data-tablewhich', options.id);
            div.appendChild(createToolsBar('componentsBox', ['delete', 'edit', 'thumb']));
            let el = options.refs['table'][options.refs['table'].length-1]['$el'];
            div.appendChild(el);
            return div;
        }else if(options.type == 'form'){
            div.setAttribute('data-componentstype', 'form');
            div.setAttribute('data-formwhich', options.id);
            div.appendChild(createToolsBar('componentsBox', ['delete', 'edit', 'thumb']));
            let el = options.refs['form'][options.refs['form'].length-1]['$el'];
            div.appendChild(el);
            return div;
        }else if(options.type == 'tabs'){
            div.setAttribute('data-componentstype', 'tabs');
            div.setAttribute('data-tabswhich', options.id);
            div.appendChild(createToolsBar('componentsBox', ['delete', 'document-add', 'edit', 'thumb']));
            let el = options.refs['tabs'][options.refs['tabs'].length-1]['$el'];
            div.appendChild(el);
            return div;
        }
    }
}